﻿using DAP.Adorners;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Forms = System.Windows.Forms;

namespace ZhwangTool
{
    /// <summary>
    /// AdornerUserControl.xaml 的交互逻辑
    /// </summary>
    public partial class AdornerUserControl : UserControl
    {
        public AdornerUserControl()
        {
            InitializeComponent();
      
        }

        CroppingAdorner _clp;
        FrameworkElement _felCur = null;
        Brush _brOriginal;

        double rcLeft = 0;
        double rcTop = 0;
        double rcRight = 0;
        double rcBottom = 0;
      
        
        private void UserControl_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            RefreshCropImage();
        }

        private void RemoveCropFromCur()
        {
            AdornerLayer aly = AdornerLayer.GetAdornerLayer(_felCur);
            aly.Remove(_clp);
        }

        private void AddCropToElement(FrameworkElement fel)
        {
            if (_felCur != null)
            {
                RemoveCropFromCur();
            }
            Rect rcInterior = new Rect(
                fel.ActualWidth * 0.2,
                fel.ActualHeight * 0.2,
                fel.ActualWidth * 0.6,
                fel.ActualHeight * 0.6);
            AdornerLayer aly = AdornerLayer.GetAdornerLayer(fel);
            _clp = new CroppingAdorner(fel, rcInterior);

            _clp.ClipToBounds = true;
            
            aly.Add(_clp);
            imgCrop.Source = _clp.BpsCrop();
            _clp.CropChanged += CropChanged;
            _felCur = fel;
            if (rbRed.IsChecked != true)
            {
                SetClipColorGrey();
            }
        }
        
        public void RefreshCropImage()
        {
            if (_clp != null)
            {
                Rect rc = _clp.ClippingRectangle;

                tblkClippingRectangle.Text = string.Format(
                    "Clipping Rectangle: ({0:N1}, {1:N1}, {2:N1}, {3:N1})",
                    rc.Left,
                    rc.Top,
                    rc.Right,
                    rc.Bottom);
                imgCrop.Source = _clp.BpsCrop();

                rcLeft = rc.Left;
                rcTop = rc.Top;
                rcRight = rc.Right;
                rcBottom = rc.Bottom;
            }
        }

        private void CropChanged(Object sender, RoutedEventArgs rea)
        {
            RefreshCropImage();
        }



        private void SetClipColorRed()
        {
            if (_clp != null)
            {
                _clp.Fill = _brOriginal;
            }
        }

        private void SetClipColorGrey()
        {
            if (_clp != null)
            {
                Color clr = Colors.Black;
                clr.A = 110;
                _clp.Fill = new SolidColorBrush(clr);
            }
        }

        private void Red_Checked(object sender, RoutedEventArgs e)
        {
            SetClipColorRed();
        }

        private void Grey_Checked(object sender, RoutedEventArgs e)
        {
            SetClipColorGrey();
        }

        private void SelectPicture_Click(object sender, RoutedEventArgs e)
        {
            
            Forms.OpenFileDialog openFileDialog = new Forms.OpenFileDialog();

            // 设置文件类型过滤器，只允许用户选择图片文件  
            openFileDialog.Filter = "Image Files (*.jpg, *.jpeg, *.gif, *.bmp, *.png)|*.jpg;*.jpeg;*.gif;*.bmp;*.png";

            // 显示文件选择对话框，并获取用户选择的文件路径  
            if (openFileDialog.ShowDialog() == Forms.DialogResult.OK)
            {

                TransformGroup group = ImageComparePanel.FindResource("ImageCompareResources") as TransformGroup;

                var tgnew = group.CloneCurrentValue();

                float angle = 0;

                if (tgnew != null)
                {
                    RotateTransform rt = tgnew.Children[2] as RotateTransform;

                    rt.Angle = 0;

                    group.Children[2] = rt;


                }

                string selectedFilePath = openFileDialog.FileName;
                // 在这里使用用户选择的图片文件路径  
                //MessageBox.Show("Selected image: " + selectedFilePath);

                using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(selectedFilePath))
                {

                    imgChurch.Source = BitmapToBitmapImage(bitmap);

                    filePath.Text = selectedFilePath;
                }

                if (imgChurch != null)
                {
                    AddCropToElement(imgChurch);

                    _brOriginal = _clp.Fill;
                    RefreshCropImage();
                 
                }

                ImageSource imageSource = imgChurch.Source;

                BitmapSource bitmapSource = imageSource as BitmapSource;

                if (bitmapSource != null)
                {
                    dpix.Text = bitmapSource.DpiX.ToString("0.00") + "--" + bitmapSource.DpiY.ToString("0.00");
                    dpiy.Text = bitmapSource.PixelHeight.ToString("0.00") + "--" + bitmapSource.Height.ToString("0.00");

                }
                
            }
        }

        /// <summary>
        /// 图片转换
        /// </summary>
        /// <param name="bitmap">bitmap格式图片</param>
        /// <returns></returns>
        private static BitmapImage BitmapToBitmapImage(System.Drawing.Bitmap bitmap)
        {
            BitmapImage bitmapImage = new BitmapImage();
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

                bitmapImage.BeginInit();
                bitmapImage.StreamSource = ms;
                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapImage.EndInit();
                bitmapImage.Freeze();
            }
            return bitmapImage;
        }


        private void SavePicture_Click(object sender, RoutedEventArgs e)
        {
            TransformGroup group = ImageComparePanel.FindResource("ImageCompareResources") as TransformGroup;

            var tgnew = group.CloneCurrentValue();

            float angle = 0;

            if (tgnew != null)
            {
                RotateTransform rt = tgnew.Children[2] as RotateTransform;

                angle =(float) rt.Angle % 360;

                MessageBox.Show(angle.ToString());
            }



            Forms.SaveFileDialog saveFileDialog = new Forms.SaveFileDialog();

            saveFileDialog.Filter = "Image Files (*.jpg, *.jpeg, *.gif, *.bmp, *.png)|*.jpg;*.jpeg;*.gif;*.bmp;*.png";

            Forms.DialogResult dialogResult = saveFileDialog.ShowDialog();

            string obImageFile = string.Empty;

            if (dialogResult == Forms.DialogResult.OK)
            {
                obImageFile = saveFileDialog.FileName;
                
            }

            string sourceImageFile = filePath.Text;


            if (System.IO.File.Exists(sourceImageFile))
            {
                using (System.Drawing.Image imageOb = System.Drawing.Image.FromFile(sourceImageFile))
                {
                    #region 尝试完善

                    //目标效果,即界面选取框相对于界面的坐标以及宽高，界面像素600*600

                    //MessageBox.Show(rcLeft.ToString()+"--"+rcRight.ToString()+"--"+rcTop.ToString()+"--"+rcBottom.ToString());

                    //x1 y1 相当于图片左上角点的矩形左上角点坐标
                    double x1 = rcLeft;
                    double y1 = rcTop;

                    //width1 height1 根据左上右下角点计算Adorner 的场合款
                    double width1 = rcRight - rcLeft;
                    double height1 = rcBottom - rcTop;
                    
                    // 获取图片的宽度和高度  
                    double widthImage = imageOb.Width;

                    double heightImage = imageOb.Height;

                    MessageBox.Show("原始图片的分辨率是" + imageOb.HorizontalResolution.ToString());

                    //Image控件被设置成Uniform时会自动将原图缩放，此时需要求出原图与控件呈现图的缩放比例offset

                    double width3 = imgChurch.ActualWidth;
                    //double imagewidth = imgChurch.Source.Width;
                    //double offset = imagewidth / width3;

                    double offset = widthImage / width3;


                    //MessageBox.Show("ActualWidth" + width3.ToString() + "显示宽度<" + imagewidth.ToString() + ">");

                    //MessageBox.Show(offset.ToString() + "<" + scaleX.ToString() + ">---<" + scaleY.ToString() + ">");

                    //scaleX = 1;
                    //scaleY = 1;

                    //old
                    //计算原图的裁剪位置以及宽高
                    //double x = ((x1 - x2) / scaleX) * offset;
                    //double y = ((y1 - y2) / scaleY) * offset;
                    //double width = (width1 / scaleX) * offset;
                    //double height = (height1 / scaleY) * offset;
                    //new

                    double x = x1 * offset;

                    double y = y1 * offset;

                    double width = width1 * offset;

                    double height = height1 * offset;

                    MessageBox.Show("width=" + width.ToString());

                    MessageBox.Show("height=" + height.ToString());

                    #endregion

                    try
                    {

                        if (angle%180==0)
                        {
                            var returnBitmap = new System.Drawing.Bitmap((int)width, (int)height, imageOb.PixelFormat);

                            returnBitmap.SetResolution(imageOb.HorizontalResolution, imageOb.VerticalResolution);

                            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(returnBitmap);

                            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

                            if (angle == 0)
                            {
                                System.Drawing.Rectangle resultRectangle = new System.Drawing.Rectangle(0, 0, (int)width, (int)height);

                                System.Drawing.Rectangle sourceRectangle = new System.Drawing.Rectangle((int)(x), (int)(y), (int)(width), (int)(height));

                                g.DrawImage(imageOb, resultRectangle, sourceRectangle, System.Drawing.GraphicsUnit.Pixel);

                                returnBitmap.Save(obImageFile);

                            }

                            if (angle == 180)
                            {
                                g.TranslateTransform((float)width / 2, (float)height / 2);

                                g.RotateTransform(angle);

                                g.TranslateTransform(-(float)width / 2, -(float)height / 2);


                                System.Drawing.Rectangle resultRectangle = new System.Drawing.Rectangle(0, 0, (int)width, (int)height);

                                System.Drawing.Rectangle sourceRectangle = new System.Drawing.Rectangle((int)(x), (int)(y), (int)(width), (int)(height));

                                g.DrawImage(imageOb, resultRectangle, sourceRectangle, System.Drawing.GraphicsUnit.Pixel);

                                returnBitmap.Save(obImageFile);

                            }

                        }
                        else
                        {
                            var returnBitmap = new System.Drawing.Bitmap((int)height, (int)width, imageOb.PixelFormat);

                            returnBitmap.SetResolution(imageOb.HorizontalResolution, imageOb.VerticalResolution);

                            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(returnBitmap);

                            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;


                            if (angle == 90 ||angle==270)
                            {
                                g.TranslateTransform((float)height / 2, (float)width / 2);

                                g.RotateTransform(angle);

                                g.TranslateTransform((float)-width / 2, (float)-height / 2);

                                System.Drawing.Rectangle resultRectangle = new System.Drawing.Rectangle(0, 0, (int)width, (int)height);

                                System.Drawing.Rectangle sourceRectangle = new System.Drawing.Rectangle((int)(x), (int)(y), (int)(width), (int)(height));
                                
                                g.DrawImage(imageOb, resultRectangle, sourceRectangle, System.Drawing.GraphicsUnit.Pixel);

                                returnBitmap.Save(obImageFile);

                            }
                        }
            
                    }
                    catch (Exception)
                    {
                    }
                }
            }


        }

        private void ImgChurch_MouseWheel(object sender, System.Windows.Input.MouseWheelEventArgs e)
        {


            Image image = sender as Image;

            if (image == null)
            {
                return;
            }

            TransformGroup group = ImageComparePanel.FindResource("ImageCompareResources") as TransformGroup;

            var tgnew = group.CloneCurrentValue();

            double angle = 0;

            if (tgnew != null)
            {
                RotateTransform rt = tgnew.Children[2] as RotateTransform;

                angle = rt.Angle % 360;
                
            }

            Point point = e.GetPosition(image);

            //MessageBox.Show(point.X.ToString("0.00")+"---"+point.Y.ToString("0.00"));

            point = new Point(point.X - image.ActualWidth / 2, point.Y - image.ActualHeight / 2);
  
            double scale = e.Delta * 0.001;

            ZoomImage(group, point, scale);


            ImageSource imageSource = imgChurch.Source;

            BitmapSource bitmapSource = imageSource as BitmapSource;

            if (bitmapSource != null)
            {
                dpix.Text = bitmapSource.DpiX.ToString("0.00") + "--" + bitmapSource.DpiY.ToString("0.00");
                dpiy.Text = bitmapSource.PixelHeight.ToString("0.00") + "--" + bitmapSource.Height.ToString("0.00")+"***"+imgChurch.ActualWidth.ToString("0.00");

            }

            RefreshCropImage();


        }

        private static void ZoomImage(TransformGroup group, Point point, double scale)
        {

            Point pointToContent = group.Inverse.Transform(point);

            ScaleTransform transform = group.Children[0] as ScaleTransform;

       

            if (transform.ScaleX + scale < 0.5)
            {
                return;
            }

            transform.ScaleX += scale;
            transform.ScaleY += scale;

            TranslateTransform transform1 = group.Children[1] as TranslateTransform;

            transform1.X = -1 * ((pointToContent.X * transform.ScaleX) - point.X);

            transform1.Y = -1 * ((pointToContent.Y * transform.ScaleY) - point.Y);

        }



        private bool isMouseLeftButtonDown;
        private Point previousMousePoint;

        /// <summary>
        /// 暂时未用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ImgChurch_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            Image image = sender as Image;

            if (image == null)
            {
                return;
            }

            if (this.isMouseLeftButtonDown && e.LeftButton == System.Windows.Input.MouseButtonState.Pressed)
            {
                this.DoImageMove(image, e.GetPosition(image));
            }
        }


        /// <summary>
        /// 暂时未用
        /// </summary>
        /// <param name="image"></param>
        /// <param name="position"></param>
        private void DoImageMove(Image image, Point position)
        {

            TransformGroup group = ImageComparePanel.FindResource("ImageCompareResources") as TransformGroup;

            TranslateTransform transform = group.Children[1] as TranslateTransform;

            transform.X += position.X - this.previousMousePoint.X;

            transform.Y += position.Y - this.previousMousePoint.Y;

            this.previousMousePoint = position;
        }

        private Cursor oldCursor;


        /// <summary>
        /// 暂时未用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ImgChurch_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            Image img = sender as Image;

            if (img == null) return;

            this.oldCursor = this.Cursor;

            this.Cursor = Cursors.SizeAll;

            img.CaptureMouse();
            this.isMouseLeftButtonDown = true;
            this.previousMousePoint = e.GetPosition(img);
        }

        /// <summary>
        /// 暂时未用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ImgChurch_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Image img = sender as Image;

            if (img == null) return;

            this.Cursor = this.oldCursor;

            img.ReleaseMouseCapture();
            this.isMouseLeftButtonDown = false;
        }



        private void BorderPic_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            //Border border = sender as Border;

            //TransformGroup group = ImageComparePanel.FindResource("ImageCompareResources") as TransformGroup;

            //Point point = e.GetPosition(border);

            //point = new Point(point.X - border.ActualWidth / 2, point.Y - border.ActualHeight / 2);


            ////point = new Point(0, 0);

            ////MessageBox.Show("wo yunxing le 11111 ");

            //double scale = e.Delta * 0.001;

            //ZoomImage(group, point, scale);

            //MessageBox.Show("wo yunxing le ");

            //RefreshCropImage();           

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
       
            RotateLeft(imgChurch);

        }

        /// <summary>
        /// 图片左转
        /// </summary>
        /// <param name="img">被操作的前台Image控件</param>
        public void RotateLeft(Image img)
        {
            TransformGroup tg = ImageComparePanel.FindResource("ImageCompareResources") as TransformGroup;

            //TransformGroup tg = img.RenderTransform as TransformGroup;

            var tgnew = tg.CloneCurrentValue();

            if (tgnew != null)
            {
                RotateTransform rt = tgnew.Children[2] as RotateTransform;
                
                img.RenderTransformOrigin = new Point(0.5, 0.5);

                rt.Angle += 90;

                tg.Children[2] = rt;

            }
            
        }

      

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {

            string str = System.Environment.CurrentDirectory;

            str = System.IO.Path.Combine(str, "Resources", "MtnChurch.jpg");

            if (System.IO.File.Exists(str))
            {
                filePath.Text = str;
            }
      
        }

        private void ImgChurch_Loaded(object sender, RoutedEventArgs e)
        {

            
            ImageSource imageSource = imgChurch.Source;

            BitmapSource bitmapSource = imageSource as BitmapSource;

            if (bitmapSource!=null)
            {
                dpix.Text = bitmapSource.DpiX.ToString("0.00")+"--"+ bitmapSource.DpiY.ToString("0.00");
                dpiy.Text = bitmapSource.PixelHeight.ToString("0.00") + "--" + bitmapSource.Height.ToString("0.00")+imgChurch.Height.ToString("0.00");
                
            }
            
        }

        private void ImgChurch_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (imgChurch != null)
            {
                AddCropToElement(imgChurch);

                _brOriginal = _clp.Fill;
                RefreshCropImage();
            

            }

        }


        private void GeiButton_Click(object sender, RoutedEventArgs e)
        {
            //只有控件大小变化，ActualHeight、ActualWidth 才会变化；
            MessageBox.Show(imgChurch.ActualHeight.ToString("0.00")+"||"+imgChurch.ActualWidth.ToString("0.00"));


            AddCropToElement(imgChurch);
            

        }

        private void GetSizeBorder_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(borderPic.ActualWidth.ToString("0.0") + "borderPic--ActualWidth--ActualHeight" + borderPic.ActualHeight.ToString("0.0"));

            AdornerLayer adornerLayer = AdornerLayer.GetAdornerLayer(imgChurch);

            Adorner[] adorners = adornerLayer.GetAdorners(imgChurch);
            if (adorners != null)
            {
                CroppingAdorner croppingAdorner = adorners[0] as CroppingAdorner;

                MessageBox.Show(croppingAdorner.ActualWidth.ToString("0.0")+ "croppingAdorner--ActualWidth--ActualHeight" + croppingAdorner.ActualHeight.ToString("0.0"));

                var rec = croppingAdorner.ClippingRectangle;

             



                //MessageBox.Show(rec.Width.ToString() +"----"+ rec.Height.ToString());

                //var renderTransform = croppingAdorner.RenderTransform;

                //MessageBox.Show(croppingAdorner.RenderSize.Width.ToString()+"--"+croppingAdorner.RenderSize.Height.ToString());

                //TransformGroup tg = croppingAdorner.RenderTransform as TransformGroup;

                //var tt = croppingAdorner.RenderTransform;

                //if (tg!=null)
                //{
                //    var trans = tg.Children[0] as ScaleTransform;

                //    MessageBox.Show(trans.ScaleX.ToString()+"--"+trans.ScaleY.ToString());

                //}
                //MessageBox.Show(croppingAdorner.AdornedElement.RenderSize.Width.ToString("0.00")+"-|-"+ croppingAdorner.AdornedElement.RenderSize.Height.ToString("0.00"));

                Image image = croppingAdorner.AdornedElement as Image;

                if (image!=null)
                {
                    TransformGroup tg = image.RenderTransform as TransformGroup;

                    if (tg != null)
                    {
                        var trans = tg.Children[0] as ScaleTransform;

                        MessageBox.Show(trans.ScaleX.ToString() + "ScaleX--ScaleY" + trans.ScaleY.ToString());

                    }





                }







            }





        }


        private void ImgChurch_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                //e.Effect = DragDropEffects.All;    //重要代码：表明是所有类型的数据，比如文件路径

                e.Effects = DragDropEffects.Link;
            
            else
                e.Effects = DragDropEffects.None;

        }

        private void ImgChurch_Drop(object sender, DragEventArgs e)
        {
            string[] filePaths = (string[])e.Data.GetData(DataFormats.FileDrop);

            if (filePaths != null && filePaths.Length > 0)
            {
                string selectedFilePath = filePaths[0];

                string fileExtension = System.IO.Path.GetExtension(selectedFilePath).ToLower();


                string[] imageExtensions = { ".jpg", ".jpeg", ".png", ".bmp"};

                if (imageExtensions.Contains(fileExtension))
                {
                    filePath.Text = selectedFilePath;

                    //MessageBox.Show(filePath.Text);

                    using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(filePath.Text))
                    {
                        imgChurch.Source = BitmapToBitmapImage(bitmap);
                        
                    }

                }

                
            }
            
        }
    }
}
